import threading
import json
import logging

# 模拟数据库存储
tickets_db = {}
tokens_db = {}
devices_db = {
    'AQM-503-01': {
        'status': 'active',
        'signature_secret': 'device-secret-key'
    }
}
user_devices_db = {}
storage_lock = threading.Lock()
logger = logging.getLogger('AuthAPI') 

def save_user_device_to_file():
    """保存用户设备绑定关系到文件"""
    try:
        with open('user_devices.json', 'w', encoding='utf-8') as f:
            json.dump(user_devices_db, f, ensure_ascii=False, indent=2)
        logger.info(f"用户设备绑定关系已保存: 总数={len(user_devices_db)}")
        return True
    except Exception as e:
        logger.error(f"保存用户设备绑定关系失败: {str(e)}")
        return False

def load_user_device_from_file():
    try:
        with open('user_devices.json', 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        logger.error("文件不存在，初始化空数据库")
        return {}
    except Exception as e:
        logger.error(f"读取用户绑定信息失败: {str(e)}")
        return {}